import {
  memo,
  forwardRef,
  useImperativeHandle,
  useState,
  useEffect,
} from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useLocation } from "react-router-dom";
import { HandleLoginWrapper } from "../style";
import { Form, Input, message, Button, Checkbox } from "antd";
import store, { fetchDepartmentThunk, fetchGetUserListThunk, fetchMenuThunk, fetchUserDetail, fetchUserLoginThunk } from "@/store";
import { ThunkDispatch } from "@reduxjs/toolkit";
import { Console } from "console";

// import pullze from "@/assets/img/"
const Account = memo(
  forwardRef((props: { children: any }, ref) => {
    // 状态管理
    const dispatch = useDispatch<ThunkDispatch<any, any, any>>();
    const navigate = useNavigate();
    const _ = useLocation();
    const [form] = Form.useForm();
    const [messageApi, contextHolder] = message.useMessage();
    // 帐号信息
    const [account, setAccount] = useState("");
    // 密码信息
    const [password, setPassword] = useState("");
    // 验证数据通过
    const onFinish = async () => {
      const obj = { user_name: account, password };
      const res = await dispatch(fetchUserLoginThunk(obj));
      if (!res ||res.payload.code == 1 || !res.payload) {
        messageApi.error("登录失败！");
        return;
      }
      const id = res.payload.data.id
      await dispatch(fetchUserDetail(id))
      await dispatch(fetchGetUserListThunk());
      await dispatch(fetchDepartmentThunk());
      await dispatch(fetchMenuThunk(id));
      messageApi.success(res.payload.msg);
      navigate("/home/index")
    };
    // 验证数据不通过
    const onFinishFailed = (errorInfo: any) => {
      messageApi.error("验证失败!请填写正确的信息~");
    };
    // 验证数据是否正确
    function handleVerifyForm() {
      form.submit();
    }
    // 设置登录信息
    function setLoginInfo() {
      let info: any = localStorage.getItem("weWin-account");
      if (info) {
        info = JSON.parse(info);
        form.setFieldsValue(info);
        setAccount(info.account.trim());
        setPassword(info.password.trim());
      }
    }
    // 初始化检查
    useEffect(() => {
      setLoginInfo();
      const token = localStorage.getItem("token");
      if (token) {
        if (!_.search == false) {
          navigate(_.search.replace("?", ""));
        } else {
          navigate("/home/index");
        }
      }
    }, []);
    // 暴露子组件的方法
    useImperativeHandle(ref, () => {
      return {
        setLoginInfo,
        handleVerifyForm,
      };
    });

    return (
      <HandleLoginWrapper>
        {contextHolder}
        <Form
          preserve={false}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            rules={[{ required: true, message: "请输入帐号" }]}
            label="帐号"
            name="account"
          >
            <Input
              value={account}
              onChange={(event) => {
                localStorage.setItem(
                  "weWin-account",
                  JSON.stringify({
                    account: event.target.value.trim(),
                    password: password.trim(),
                  })
                );
                setAccount(event.target.value.trim());
              }}
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: "请输入密码" }]}
            label="密码"
            name="password"
          >
            <Input.Password
              value={password}
              onChange={(event) => {
                localStorage.setItem(
                  "weWin-account",
                  JSON.stringify({
                    account: account.trim(),
                    password: event.target.value.trim(),
                  })
                );
                setPassword(event.target.value.trim());
              }}
            ></Input.Password>
          </Form.Item>
          <Form.Item className={"relative"}>
            <div className="flex justify-around -mt-3 mb-3">
              {props.children}
            </div>
            <Button type="primary" onClick={() => handleVerifyForm()}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </HandleLoginWrapper>
    );
  })
);
export default Account;
